# coding:utf-8

import os
import datetime

import xlwt
from flask import request, render_template, send_file, abort

from .models import WarZoneDailyStatic
from .forms import SearchWarZoneStatForm
from . import war_zone_bp


@war_zone_bp.route('/stat_list', methods=['GET', 'POST'])
def zone_stat_list():
    """
    created by chenhj at 22/12/2017

    """
    form = SearchWarZoneStatForm(formdata=request.form or request.args)

    query = WarZoneDailyStatic.query.filter_by(deleted_at=0)
    url_kwargs = {}
    if form.validate():
        query_kwargs, url_kwargs = form.generate_kwargs()

        query = WarZoneDailyStatic.generate_list_query_condition(
            args=query_kwargs,
            query=query
        )

    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(WarZoneDailyStatic.date.desc()).paginate(
        page, per_page=1000,
        error_out=False)
    data = pagination.items

    return render_template(
        'stat/stat_list.html',
        form=form,
        data=data,
        pagination=pagination,
        url_kwargs=url_kwargs,
    )


@war_zone_bp.route('/export_zone_stat_list', methods=['GET', 'POST'])
def export_zone_stat_list():
    form = SearchWarZoneStatForm(formdata=request.form or request.args)

    template_path = '/tmp/zone_stat_{}.xls'.format(datetime.datetime.now())
    book = xlwt.Workbook(encoding='utf-8')
    fields = [
        '战区', '日期', '销售额', '付费人数', '平均付费', '订单数', '发布次数',
        '抢单次数', '抢单人数', '派单人数', '消耗派单点', '锁定次数', '消费汇币',
        '消费人数', '平均消费', '退返汇币', '退返人数', '平均退返', '退返派单点',
        '退返人数', '总人数', '取关人数', '新增人数'
    ]

    sheet = book.add_sheet('用户列表')

    for index, value in enumerate(fields):
        sheet.write(0, index, value)

    # write content
    query = WarZoneDailyStatic.query.filter_by(deleted_at=0)
    if form.validate():
        query_kwargs, url_kwargs = form.generate_kwargs()
        query = WarZoneDailyStatic.generate_list_query_condition(
            args=query_kwargs,
            query=query
        )

    data = [
        (
            each.war_zone.name,
            str(each.date),
            each.sales,
            each.pay_people_cnt,
            round(each.sales / each.pay_people_cnt) if each.pay_people_cnt > 0 else 0,
            each.ro_cnt,
            each.published_count,
            each.bid_cnt,
            each.bid_people_cnt,
            each.dispatch_people_cnt,
            each.cost_dispatch_point,
            each.locked_cnt,
            each.cost_bid_point,
            each.cost_bid_people_cnt,
            round(each.cost_bid_point / each.cost_bid_people_cnt) if each.cost_bid_people_cnt > 0 else 0,

            each.return_bid_point,
            each.return_bid_people_cnt,

            round(each.return_bid_point / each.return_bid_people_cnt) if each.return_bid_people_cnt > 0 else 0,

            each.return_dispatch_point,
            each.return_dispatch_people_cnt,
            each.people_cnt,
            each.cancel_attend_cnt,
            each.attend_cnt,
        ) for each in query.order_by(WarZoneDailyStatic.date.desc()).all()
    ]

    for index, each in enumerate(data):
        for num, value in enumerate(each):
            sheet.write(index+1, num, value)
    book.save(template_path)
    if not os.path.exists(template_path):
        abort(404)
    return send_file(template_path, as_attachment=True)
